package com.hnepri.fang.ftx2.fetch.index;

import com.hnepri.fang.ftx2.fetch.IPage;
import com.hnepri.util.StringUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.HashMap;
import java.util.Map;

public class ResidentialIndexPageImpl implements IPage {

    private String getResidentialRanking(Document doc) {
        Elements eles = doc.select("body>div.laybox");
        String info = null;
        for (Element node: eles) {
            Elements cnodes = node.select("div.allbigtit span.rother a");
            if (cnodes == null || cnodes.size() == 0) continue;
            String flag = cnodes.get(0).text().trim();
            if ("查看评级详情".equals(flag)) {
                info = getInfo(node);
                break;
            }
        }
        return info;
    }
    private String getInfo(Element ele) {
        StringBuilder sb = new StringBuilder();

        Elements eles = ele.select("div.w1200b div.s1 i");
        float level = 0;
        for (int i = 0; i < eles.size(); i++) {
            Element iEle = eles.get(i);
            String cls = StringUtil.null2empty(iEle.attr("class"));
            if (cls.equals("")) {
                level += 1;
            } else if (cls.equals("half")) {
                level += 0.5;
            }
        }
        sb.append("level:" + level + "|");
        eles = ele.select("div.w1200b div.s3 p");
        for (int i = 0; i < eles.size(); i++) {
            Element pEle = eles.get(i);
            String type = pEle.select("span>b").text();
            String detail = "";
            if (pEle.childNodeSize() > 1 && pEle.childNode(1) != null) {
                detail = pEle.childNode(1).toString();
            }
            sb.append(type + ":" + detail + "|");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
    @Override
    public String parse(String html) {
        Document doc = Jsoup.parseBodyFragment(html);
        String info = this.getResidentialRanking(doc);
        return info;
    }
}
